// 紧急程度 新增/编辑
import type { FormInstance } from 'element-plus'
import type { OrserSetOption, formNameAndValueStateType } from '../typings'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { ElDialog, ElForm, ElFormItem, ElButton, ElInput, ElMessage } from 'element-plus'
import { handleTrim } from '~/utils/util'
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'EmergencyDegreeOption',
  props: ['visible', 'title', 'record', 'original', 'allName', 'emergencyDegreeKey'],
  emits: ['cancel', 'getCfgTypeName'],
  setup(props: OrserSetOption, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>() // 表单
    const formState = reactive<formNameAndValueStateType['form']>({})
    Object.assign(formState, props.record)

    // 提交前
    const updOrEditSubmit = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          // 去输入的前后空格
          formState.cfgTypeName = handleTrim(formState.cfgTypeName ?? '')

          if (props.title === '新增工单紧急程度管理') {
            if (props.allName?.indexOf(formState.cfgTypeName) !== -1) {
              ElMessage({
                message: '此紧急程度 已存在',
                type: 'warning'
              })
            } else {
              addSubmit()
            }
          }
          if (props.title === '编辑工单紧急程度管理') {
            if (
              props.original !== formState.cfgTypeName &&
              props.allName?.indexOf(formState.cfgTypeName) !== -1
            ) {
              ElMessage({
                message: '此紧急程度 已存在',
                type: 'warning'
              })
            } else {
              editSubmit()
            }
          }
        } else {
          return false
        }
      })
    }

    // 编辑->确定
    const editSubmit = async () => {
      const realForm = JSON.parse(JSON.stringify(formState))
      if (realForm.cfgValue) {
        delete realForm.cfgValue
      }
      realForm.cfgValue = parseInt(formState.cfgValue!)
      realForm.cfgTypeCode = props.emergencyDegreeKey
      // 点"确定"后调接口保存编辑内容 并刷新
      const res = await store.dispatch('order/PostOrderSetUpdate', realForm)
      if (res?.code === 200) {
        handleCloseModal()
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    // 新增->确定
    const addSubmit = async () => {
      const realForm = {
        cfgTypeName: formState.cfgTypeName,
        cfgValue: parseInt(formState.cfgValue!),
        cfgTypeCode: props.emergencyDegreeKey
      }
      const res = await store.dispatch('order/PostOrderSetAdd', realForm)
      if (res?.code === 200) {
        handleCloseModal()
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 处理时长
    const handleTimeOnInput = () => {
      if (parseInt(formState.cfgValue!) > 48 || parseInt(formState.cfgValue!) < 1) {
        formState.cfgValue = ''
      }
      formState.cfgValue = formState.cfgValue?.replace(/[^\d]/g, '')
    }

    return () => {
      const { title, visible } = props

      return (
        <ElDialog
          title={title}
          modelValue={visible!}
          append-to-body
          width="400px"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
        >
          <ElForm
            ref={ruleFormRef}
            model={formState}
            label-width="100px"
            class={styles['orderSet-assess']}
          >
            <ElFormItem
              label="紧急程度"
              prop="cfgTypeName"
              rules={[{ required: true, message: '请输入工单紧急程度', trigger: 'change' }]}
            >
              <ElInput
                class={styles['orderSet-input']}
                v-model={formState.cfgTypeName}
                placeholder="请输入工单紧急程度"
                clearable
                disabled={formState.status === 1}
              />
            </ElFormItem>
            <ElFormItem
              label="处理时长"
              prop="cfgValue"
              rules={[
                { required: true, message: '请输入处理时间(1至48的正整数)', trigger: 'change' }
              ]}
            >
              <ElInput
                clearable
                class={styles['orderSet-input']}
                v-model={formState.cfgValue}
                onInput={handleTimeOnInput}
                placeholder="请输入1至48的正整数"
              >
                {{
                  suffix: () => <span class={styles['orderSet-hours']}>小时</span>
                }}
              </ElInput>
            </ElFormItem>
          </ElForm>
          <div class={styles['confirm-button']}>
            <ElButton class={styles['confirm-button-cancel']} plain onClick={handleCloseModal}>
              取 消
            </ElButton>
            <ElButton
              class={styles['confirm-button-submit']}
              type="primary"
              onClick={() => updOrEditSubmit(ruleFormRef.value)}
            >
              确 定
            </ElButton>
          </div>
        </ElDialog>
      )
    }
  }
})
